package org.xcorpio.java8.chapter11;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class AsynchorousMethod {

    public static Future<String> getXxxAsync(String id) {
        CompletableFuture<String> future = new CompletableFuture<>();
        new Thread(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                // throw new RuntimeException("HAHA");
                future.complete(id);
            } catch (Exception e) {
                future.completeExceptionally(e);
            }
        }).start();
        return future;
    }

    public static void main(String[] args) {
        Future<String> future = getXxxAsync("Hi");
        System.out.println("do something else...");
        System.out.println(future);
        try {
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        CompletableFuture<String> supplyAsync = CompletableFuture.supplyAsync(() -> {
            return "supplyAysnc CompletableFuture";
        });
        try {
            System.out.println(supplyAsync.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
